<?php

namespace app\model;

use app\common\controller\PreciseCalculator;
use think\Exception;
use think\facade\Db;

class OrderModel extends BaseModel
{
    protected $name = 'dingdan';


    public const TYPE_DZ = 100; //定制产品
    public const TYPE_BZ = 200; //标准产品

    public const STATUS_WAIT = 100; //待发起审批
    public const STATUS_ING = 200; //审批中
    public const STATUS_FAIL = 300; //被驳回
    public const STATUS_SUCCESS = 400; //成功


    public const STATUS_LIST = [
        [
            'status' => self::STATUS_WAIT,
            'name' => '待发起审批'
        ],
        [
            'status' => self::STATUS_ING,
            'name' => '审批中'
        ],
        [
            'status' => self::STATUS_FAIL,
            'name' => '被驳回'
        ],
        [
            'status' => self::STATUS_SUCCESS,
            'name' => '成功'
        ]
    ];

    /**
     * Notes: 添加销售订单
     * User: chenLei
     * Date: 9/9/25
     * @param $params
     * @return bool
     */
    public function add($params)
    {
        if ($this->where('dingdan_code', $params['dingdan_code'])->count()) {
            $this->error = '重复的订单号';
            return false;
        }

        $bom = [];
        $order_price = 0;
        foreach ($params['bom'] as $item) {
            $material = MaterialCategoryModel::where('id', $item['material_id'])->findOrEmpty();
            if ($material->isEmpty()) {
                $this->error = '不存在的物料，请重新选择bom清单';
                return false;
            }
            $sum_price = PreciseCalculator::mul($item['price'], $item['material_quantity']);
            $order_price = PreciseCalculator::add($order_price, $sum_price);
            $bom[] = [
                'material_id' => $material['id'],
                'material_name' => $material['material_name'],
                'material_quantity' => $item['material_quantity'],
                'price' => $item['price'],
                'sum_price' => $sum_price,
                'create_time' => date('Y-m-d H:i:s'),
                'update_time' => date('Y-m-d H:i:s'),
            ];
        }


        if (count($bom) <= 0) {
            $this->error = '请添加bom清单';
            return false;
        }

        $order_amount = PreciseCalculator::mul($order_price, $params['quantity']);

        Db::startTrans();
        try {

            $this->save([
                'user_id' => $params['login_user_id'] ?? 0,
                'dingdan_code' => $params['dingdan_code'],
                'dingdan_date' => $params['dingdan_date'],
                'product_type' => $params['product_type'],
                'product_id' => $params['product_id'] ?? 0,
                'product_name' => $params['product_name'],
                'customer_id' => $params['customer_id'],
                'quantity' => $params['quantity'] ?? 1,
                'delivery_date' => $params['delivery_date'],
                'technical_requirements' => $params['technical_requirements'] ?? '',
                'design_drawings' => $params['design_drawings'] ?? '',
                'remarks' => $params['remarks'] ?? '',
                'price' => $order_price,
                'amount' => $order_amount,
                'dingdan_status' => self::STATUS_WAIT,
            ]);

            foreach ($bom as &$item) {
                $item['dingdan_id'] = $this->id;
            }

            OrderBomModel::insertAll($bom);

            Db::commit();
        } catch (\Exception $exception) {
            Db::rollback();
            $this->error = $exception->getMessage();
            return false;
        }


        return true;

    }


    /**
     * Notes: 编辑订单
     * User: chenLei
     * Date: 9/9/25
     * @param $params
     * @return bool
     */
    public function edit($params)
    {
        $info = $this->where('id', $params['id'])->findOrEmpty();
        if ($info->isEmpty()) {
            $this->error = '订单信息已经不存在';
            return false;
        }

        if ($info->dingdan_status != self::STATUS_WAIT && $info->dingdan_status != self::STATUS_FAIL) {
            $this->error = '该订单状态不支持编辑修改';
            return false;
        }

        $bom = [];
        $order_price = 0;
        foreach ($params['bom'] as $item) {
            $material = MaterialCategoryModel::where('id', $item['material_id'])->findOrEmpty();
            if ($material->isEmpty()) {
                $this->error = '不存在的物料，请重新选择bom清单';
                return false;
            }
            $sum_price = PreciseCalculator::mul($item['price'], $item['material_quantity']);
            $order_price = PreciseCalculator::add($order_price, $sum_price);
            $bom[] = [
                'material_id' => $material['id'],
                'material_name' => $material['material_name'],
                'material_quantity' => $item['material_quantity'],
                'price' => $item['price'],
                'sum_price' => $sum_price,
                'create_time' => date('Y-m-d H:i:s'),
                'update_time' => date('Y-m-d H:i:s'),
            ];
        }
        if (count($bom) <= 0) {
            $this->error = '请添加bom清单';
            return false;
        }
        $order_amount = PreciseCalculator::mul($order_price, $params['quantity']);

        Db::startTrans();
        try {

            $info->save([
                'dingdan_code' => $params['dingdan_code'],
                'dingdan_date' => $params['dingdan_date'],
                'product_type' => $params['product_type'],
                'product_id' => $params['product_id'] ?? 0,
                'product_name' => $params['product_name'],
                'customer_id' => $params['customer_id'],
                'quantity' => $params['quantity'] ?? 1,
                'delivery_date' => $params['delivery_date'],
                'technical_requirements' => $params['technical_requirements'] ?? '',
                'design_drawings' => $params['design_drawings'] ?? '',
                'remarks' => $params['remarks'] ?? '',
                'price' => $order_price,
                'amount' => $order_amount,
                'dingdan_status' => self::STATUS_WAIT,
            ]);

            foreach ($bom as &$item) {
                $item['dingdan_id'] = $info['id'];
            }
            OrderBomModel::where('dingdan_id', $info['id'])->delete();
            OrderBomModel::insertAll($bom);

            Db::commit();
        } catch (\Exception $exception) {
            Db::rollback();
            $this->error = $exception->getMessage();
            return false;
        }


        return true;
    }


    /**
     * Notes: 订单详情
     * User: chenLei
     * Date: 9/9/25
     * @param $params
     * @return array|false
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function info($params)
    {
        $info = $this->where('id', $params['id'])->findOrEmpty();
        if ($info->isEmpty()) {
            $this->error = '订单信息已经不存在';
            return false;
        }

        $info = $info->toArray();
        $info['customer'] = CustomerModel::where('id', $info['customer_id'])->field('id,customer_name,phone1')
            ->find();

        $info['bom'] = OrderBomModel::where('dingdan_id', $info['id'])->select()->toArray();
        $info['sales_person'] = UserModel::where('id', $info['user_id'])->value('realname');

        return $info;

    }


    /**
     * Notes: 发起订单审批
     * User: chenLei
     * Date: 9/11/25
     * @param $params
     * @return false|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function initiateApproval($params)
    {
        $info = $this->where('id', $params['id'])->findOrEmpty();
        if ($info->isEmpty()) {
            $this->error = '订单信息已经不存在';
            return false;
        }

        if (!in_array($info->dingdan_status, [self::STATUS_WAIT, self::STATUS_FAIL])) {
            $this->error = '该状态不能发起审批';
            return false;
        }

        $approvalModel = new ApprovalModel();
        $list = $approvalModel->where('type', $info->product_type)->order('weigh')->select();
        if (empty($list) || count($list) <= 0) {
            $this->error = '该审批节点还未配置，请先配置';
            return false;
        }

        $date = date('Y-m-d H:i:s');
        Db::startTrans();
        try {
            $info->dingdan_status = self::STATUS_ING;
            $info->approval_user_id = $params['login_user_id'];
            $info->approval_time = $date;
            $info->save();

            $code = 'SP' . time() . rand(100000, 999999);
            $orderApprovalModel = new OrderApprovalModel();
            $orderApprovalId = $orderApprovalModel->insertGetId([
                'user_id' => $params['login_user_id'],
                'dingdan_id' => $info['id'],
                'code' => $code,
                'status' => OrderApprovalModel::STATUS_ING,
                'create_time' => $date,
                'update_time' => $date,
            ]);


            $approval_user_list = [];

            foreach ($list as $key => $item) {
                if ($key == 0) {
                    $status = self::STATUS_ING;
                } else {
                    $status = self::STATUS_WAIT;
                }

                $approval_user_list[] = [
                    'dingdan_id' => $info['id'],
                    'dingdan_approval_id' => $orderApprovalId,
                    'department_id' => $item['department_id'],
                    'user_id' => $item['user_id'],
                    'status' => $status,
                    'create_time' => $date,
                    'update_time' => $date,
                ];
            }

            $orderApprovalUserModel = new OrderApprovalUserModel();
            $orderApprovalUserModel->insertAll($approval_user_list);

            $orderLog = new OrderLogModel();
            $orderLog->save([
                'dingdan_id' => $info['id'],
                'dingdan_approval_id' => $orderApprovalId,
                'department_id' => 2,
                'user_id' => $params['login_user_id'],
                'remark' => '发起审批',
                'status' => OrderLogModel::INITIATE_APPROVAL,
            ]);

            Db::commit();
        } catch (Exception $exception) {
            Db::rollback();
            $this->error = $exception->getMessage();
            return false;
        }

    }


    /**
     * Notes: 撤销审批
     * User: chenLei
     * Date: 9/11/25
     * @param $params
     * @return false|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function cancel($params)
    {
        $info = $this->where('id', $params['id'])->findOrEmpty();
        if ($info->isEmpty()) {
            $this->error = '订单信息已经不存在';
            return false;
        }

        if (!in_array($info->dingdan_status, [self::STATUS_ING])) {
            $this->error = '该状态不能撤销审批';
            return false;
        }

        $approvalUser = new OrderApprovalUserModel();
        $list = $approvalUser->where('dingdan_id', $params['id'])->select();

        foreach ($list as $item) {
            if ($item['status'] != 100) {
                $this->error = '该订单已经有人审批暂时无法查看';
                return false;
            }
        }

        Db::startTrans();
        try {
            $info->dingdan_status = self::STATUS_WAIT;
            $info->save();

            $orderApprovalModel = new OrderApprovalModel();
            $orderLog = new OrderLogModel();
            $orderLog->save([
                'dingdan_id' => $info['id'],
                'dingdan_approval_id' => $orderApprovalModel->where('dingdan_id', $params['id'])->value('id'),
                'user_id' => $params['login_user_id'],
                'department_id' => 2,
                'remark' => '撤销审批',
                'status' => OrderLogModel::REVOKE,
            ]);


            $orderApprovalModel->where('dingdan_id', $params['id'])->delete();

            $orderApprovalUserModel = new OrderApprovalUserModel();
            $orderApprovalUserModel->where('dingdan_id', $params['id'])->delete();


            Db::commit();
        } catch (Exception $exception) {
            Db::rollback();
            $this->error = $exception->getMessage();
            return false;
        }
    }


    /**
     * Notes: 技术修改图纸
     * User: chenLei
     * Date: 9/15/25
     * @param $params
     * @return bool
     */
    public function updateTechnicalRequirements($params)
    {
        $info = $this->where('id', $params['id'])->findOrEmpty();
        if ($info->isEmpty()) {
            $this->error = '订单信息已经不存在';
            return false;
        }



        $info->technical_requirements = $params['technical_requirements'] ?? '';
        $info->design_drawings = $params['design_drawings'] ?? '';
        $info->save();

        return true;

    }

}